import { ElNotification } from "element-plus"
import {
	refreshToken,
	refreshTokenName,
	axiosExpiredCode,
	axiosSuccessCode,
	axiosRefreshUrl,
	axiosRefreshRequestType,
} from "/config"
import { useUserInfoStore } from "/store/userInfo"

let isRefreshing = false
const refreshList = []

export default function () {
	return new Promise((resolve, reject) => {
		if (isRefreshing) {
			refreshList.push({ resolve, reject })
			return
		}
		isRefreshing = true
		const axios = new XMLHttpRequest()
		axios.onreadystatechange = () => {
			if (axios.readyState === 4) {
				if (axios.status === 200) {
					isRefreshing = false
					const result = JSON.parse(axios.responseText)
					if (result.code === axiosSuccessCode) {
						window.localStorage.setItem("token", result.data.token)
						window.localStorage.setItem("refreshToken", result.data.refreshToken)
						resolve(result)
						refreshList.forEach(item => {
							item.resolve(result)
						})
					} else if (result.code === axiosExpiredCode) {
						const userInfoStore = useUserInfoStore()
						userInfoStore.logout()
					} else {
						ElNotification({ message: "token接口错误", type: "error" })
						reject(result)
						refreshList.forEach(item => {
							item.reject(result)
						})
					}
				}
			}
		}
		axios.open(axiosRefreshRequestType, axiosRefreshUrl)
		axios.setRequestHeader(refreshTokenName, refreshToken())
		axios.send()
	})
}
